{% extends 'base.html' %}
{% block title %}{{ content.title }}{% endblock %}
{% block nav_blog_active %}active{% endblock %}

{% block header_extends %}
    <link rel="stylesheet" href="/static/blog.css/">
    <script type="text/javascript" src="/static/ckeditor/ckeditor-init.js"></script>
    <script type="text/javascript" src="/static/ckeditor/ckeditor/ckeditor.js"></script>
{% endblock %}

{% block content %}
    <div class="container">
        <div class="row">
            <div class="col-xs-10 col-xs-offset-1">
                <h3> {{ content.title }}</h3>
                <ul class="blog-info-desc">
                    <li>作者:{{ content.author }}</li>
                    <li>博客分类:<a href="{% url 'blog_with_type' content.blog_type.pk %}">{{ content.blog_type }}</a></li>
                    <li>发表日期:{{ content.created_time }}</li>
                    <li>阅读量: {{ content.get_viewed_num }}</li>
                    <li>评论量:{{ comments_count }}</li>
                </ul>
                <div class="blog-content">{{ content.content|safe }}</div>
                <div class="like" onclick="likeChange(this,{{ content.pk }})">
                    <span class="glyphicon glyphicon-thumbs-up {% if is_like %}active{% endif %}"></span>
                    <span class='liked_num'> {{ content.get_like_num }} </span>
                    <span>喜欢</span>
                </div>

                <div class="blog-more">
                    <p>上一篇:
                        {% if previous_blog %}
                            <a href="{% url 'blog_detail' previous_blog.pk %}">{{ previous_blog.title }}</a>
                    {% else %}
                            没有了
                    {% endif %}
                    </p>
                    <p>下一篇:
                       {% if next_blog %}
                            <a href="{% url 'blog_detail' next_blog.pk %}">{{ next_blog.title }}</a>
                    {% else %}
                            没有了
                    {% endif %}</p>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-10 col-xs-offset-1">
                <div class="comment-area">
                    <h3 class="comment-area-title">提交评论</h3>
                    {% if user.is_authenticated %}
                        {# overflow:hidden 清除包含块内子元素的浮动 #}
                        <form id="comment_form" action="{% url 'update_comment' %}" method="post" style="overflow: hidden">
                            <label> {{ user.username }},欢迎评论~</label>
                            <div id="reply_content_container" style="display: none;">
                                <p id="reply_title">回复:</p>
                                <div id="reply_content"></div>
                            </div>
                            {% csrf_token %}
                            {% for field in comment_form %}
                                {{ field }}
                            {% endfor %}
                            <span id="comment_error" class="text-danger pull-left"></span>
                            <input type="submit" value="发送" class="btn btn-primary pull-right" style="float: right">
                        </form>

                    {% else %}
                        未登录
                        <a class='btn btn-primary' href="{% url 'login' %}?from={{ request.get_full_path }}">登录</a>
                        <span>or</span>
                        <a class ='btn btn-danger' href="{% url 'register' %}?from={{ request.get_full_path }}">注册</a>
                    {% endif %}
                </div>
                <div class="comment-area">
                     <h3 class="comment-area-title">评论列表</h3>
                        <div id="comment_list">
                            {% for comment in comments %}
                                 <div id="root_{{ comment.pk }}" class="comment">
                                     <span>{{ comment.user.username }}</span>
                                     <span>({{ comment.comment_time|date:'Y-m-d H:i:s' }}):</span>
                                     <div id="comment_{{ comment.pk }}">{{ comment.text|safe }}</div>
                                    <a href="javascript:reply({{ comment.pk }});">回复</a>

                                     {% for reply in comment.root_comment.all %}
                                         <div class="reply">
                                             <span>{{ reply.user.username }}</span>
                                             <span>({{ reply.comment_time|date:'Y-m-d H:i:s' }}):</span>
                                             <span>回复</span>
                                             <span>{{ reply.reply_to.username }}:</span>
                                            <div id="comment_{{ reply.pk }}">
                                                {{ reply.text|safe }}
                                            </div>
                                             <a href="javascript:reply({{ reply.pk }});">回复</a>
                                          </div>
                                     {% endfor %}


                                 </div>
                                {% empty %}
                                    <span id="no_comment">暂无评论</span>
                                {% endfor %}
                        </div>
                </div>
            </div>
        </div>

        <!-- 模态框 -->
        <div class="modal fade" id="login_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog modal-sm" role="document">
                <div class="modal-content">
                    <form id="login_modal_form" action="" method="POST">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myModalLabel">请登录</h4>
                        </div>

                        <div class="modal-body">
                            {% csrf_token %}
                            {% for field in login_form %}
                                <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                {{ field }}
                            {% endfor %}
                             <span id="login_modal_tip" class="text-danger"></span>
                        </div>
                        <div class="modal-footer">
                            <button type="submit" class="btn btn-primary">登录</button>
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

{% endblock %}

{% block script_extends %}
    <script type="text/javascript">
        $("#comment_form").submit(function () {
            //判断是否为空
            $("#comment_error").text('');
            if(CKEDITOR.instances["id_text"].document.getBody().getText().trim()==''){
                $("#comment_error").text("评论内容不能为空");
                return false;
            }
            //更新数据到textarea
            CKEDITOR.instances['id_text'].updateElement();
           //异步提交
            $.ajax({
                url: "{% url 'update_comment' %}",
                type: 'POST',
                data: $(this).serialize(),
                cache: false,
                success:function (data) {
                    console.log(data);
                    if(data['status'] == "SUCCESS"){
                        //插入数据
                        if($('#reply_comment_id').val()=='0'){
                            //插入评论
                            var comment_html = '<div id="root_' + data['pk'] + '" class="comment"><span>' + data['username'] + '</span><span> (' + data['comment_time'] + ')：</span><div id="comment_' + data['pk'] + '">' + data['text'] + '</div><a href="javascript:reply(' + data['pk'] + ');">回复</a></div>';
                            $("#comment_list").prepend(comment_html);
                        }
                        else{
                            var reply_html ='<div class="reply"><span>' + data['username'] + '</span><span> (' + data['comment_time'] + ')</span><span> 回复 </span><span>' + data['reply_to'] + '：</span><div id="comment_' + data['pk'] + '">' + data['text'] + '</div><a href="javascript:reply(' + data['pk'] + ');">回复</a></div>';
                            $("#root_" + data['root_pk']).append(reply_html);
                        }
                        //清空编辑框的内容
                        CKEDITOR.instances['id_text'].setData('');
                         $('#reply_content_container').hide();
                        $('#reply_comment_id').val('0');
                        $('#no_comment').remove();
                        $("#comment_error").text('评论成功');
                    }else{
                        //显示错误信息
                        $("#comment_error").text(data['message']);
                    }
                },
                error: function (xhr) {
                    console.log(xhr);
                }
            });
            return false;
        });

        function reply(reply_comment_id) {
            $('#reply_comment_id').val(reply_comment_id);
            var html = $("#comment_"+ reply_comment_id).html();
            $("#reply_content").html(html);
            $("#reply_content_container").show();
            $('html').animate({scrollTop:$('#comment_form').offset().top-60},300,function () {
                CKEDITOR.instances['id_text'].focus();
            });
        }

        function likeChange(obj,object_id){
            // 判断obj中是否包含active的元素，用于判断当前状态是否为激活状态
            var is_like = (obj.getElementsByClassName('active').length == 0)
            console.log(is_like);
            $.ajax({
                url:"{% url 'like_change' %}",
                type:'GET',
                data:{
                    object_id: object_id,
                    is_like: is_like
                },
                cache:false,
                success:function (data) {
                    console.log(data)
                    if(data['status'] == 'SUCCESS'){
                        var record = $(obj.getElementsByClassName('glyphicon'));
                        if(is_like){
                            record.addClass('active')
                        }
                        else{
                            record.removeClass('active');
                        }
                        //更新点赞数量
                        var liked_num = $(obj.getElementsByClassName('liked_num'));
                        liked_num.text(data['liked_num']);
                    }
                    else{
                        if(data['code'] == 400){
                            $('#login_modal').modal('show');
                        }else{
                             alert(data['message'])
                        }

                    }
                },
                error:function (xhr) {
                    console.log(xhr)
                }
            });
        }
        
        $('#login_modal_form').submit(function () {
            $.ajax({
                url: "{% url 'login_for_modal' %}",
                type: 'POST',
                data: $(this).serialize(),
                cache: false,
                success: function (data) {
                    if(data['status'] == 'SUCCESS'){
                        window.location.reload();
                    }else{
                        $('#login_modal_tip').text('用户名或密码不正确');
                    }
                }
            });
            return false;
        });
    </script>
{% endblock %}
